package com.xuchang.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuchang.domain.SysUser;
import com.xuchang.mapper.SysUserMapper;
import com.xuchang.model.R;
import com.xuchang.service.SysUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.util.Arrays;

@RestController
@RequestMapping("/users")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;


    @GetMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current" ,value = "当前页") ,
            @ApiImplicitParam(name = "size" ,value = "每页显示的条数") ,
            @ApiImplicitParam(name = "mobile" ,value = "员工的手机号码") ,
            @ApiImplicitParam(name = "fullname" ,value = "员工的全名称") ,
    })
    public R<Page<SysUser>> searchUsers(Page<SysUser> page,String mobile,String fullname){
        page.addOrder(OrderItem.desc("last_update_time"));
        return R.ok(sysUserService.searchUsers(page,mobile,fullname));
    }

    @GetMapping("/{userId}")
    public R<SysUser> getUserInfo(@PathVariable Long userId){
        SysUser sysUser = sysUserService.getById(userId);
        return R.ok(sysUser);
    }

    @PostMapping
    public R createUser(@RequestBody @Validated SysUser sysUser){
        Long l = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        sysUser.setCreateBy(l);
        boolean save = sysUserService.createUser(sysUser);
        if(save){
            return R.ok("成功");
        }
        return R.fail("失败");
    }

    @PatchMapping
    public R editUser(@RequestBody @Validated SysUser sysUser){
        Long l = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        sysUser.setCreateBy(l);
        boolean save = sysUserService.editUser(sysUser);
        if(save){
            return R.ok("成功");
        }
        return R.fail("失败");
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除用户")
    public R deleteUsers(@RequestBody Long ids[]){
        boolean b = sysUserService.deleteByIds(Arrays.asList(ids));
        if(b){
           return R.ok("成功");
        }
        return R.fail("失败");
    }
}
